package com.hengpeng.itfinoss.controller.stm;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hengpeng.common.acl.vo.Passport;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.CalendarUtil;
import com.hengpeng.common.util.MailSendUtil;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.EmailLog;
import com.hengpeng.itfinbase.persist.EmailLog.EmailState;
import com.hengpeng.itfinbase.persist.EmailLog.EmailType;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * TODO 邮件记录控制类器
 * </pre>
 * @author pengfangliang
 * @update lanmingming
 * @version 1.0, 2010-9-3
 */
@Controller
@RequestMapping("/em")
public class EmailLogController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(method = RequestMethod.POST)
	public String add(HttpServletRequest request, EmailType type, String storeId, String email, String title,
			String content, EmailState state, Date sendTime, Date successTime, Integer retryCount, ModelMap map)
	{
		Passport passport = getUserSession(request.getSession());
		EmailLog emailLog = new EmailLog();
		emailLog.setType(type);
		emailLog.setSendUserName(passport.getUserId());
//		emailLog.setStoreId(storeId);
		emailLog.setEmail(email);
		emailLog.setTitle(title);
		emailLog.setContent(content);
		emailLog.setState(state);
		emailLog.setSendTime(sendTime);
		emailLog.setSuccessTime(successTime);
		emailLog.setRetryCount(retryCount);
		try
		{
			ServiceResult<EmailLog> result = serviceFactory.getEmailLogService().add(emailLog);
			return returnSuccess(map, result, "/em/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String preAdd(ModelMap map)
	{
		map.put("emailLog", new EmailLog());
		return "stm/emaillog/detail";
	}

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, ModelMap map, String semailType, String userid, String storeId,
			String email, String title, String content, String sstate, String sendTime1, String sendTime2,
			String successTime1, String successTime2, Integer retryCount)
	{

		Date sendTimeBegin = null;
		Date sendTimeEnd = null;
		Date successTimeBegin = null;
		Date successTimeEnd = null;
		EmailState state = null;
		EmailType type = null;
		if (sendTime1 != null && sendTime1.trim().length() > 0)
			sendTimeBegin = CalendarUtil.parseFormatNoMM(sendTime1);
		if (sendTime2 != null && sendTime2.trim().length() > 0)
			sendTimeEnd = CalendarUtil.parseFormatNoMM(sendTime2);
		if (successTime1 != null && successTime1.trim().length() > 0)
			successTimeBegin = CalendarUtil.parseFormatNoMM(successTime1);
		if (successTime2 != null && successTime2.trim().length() > 0)
			successTimeEnd = CalendarUtil.parseFormatNoMM(successTime2);
		if (sstate != null && sstate.trim().length() > 0)
			state = EmailState.valueOf(sstate);
		if (semailType != null && semailType.trim().length() > 0)
			type = EmailType.valueOf(semailType);
		map.put("type", type);
		map.put("userid", userid);
		map.put("storeId", storeId);
		map.put("email", email);
		map.put("title", title);
		map.put("content", content);
		map.put("state", state);
		map.put("sendTime1", sendTime1);
		map.put("sendTime2", sendTime2);
		map.put("successTime1", successTime1);
		map.put("successTime2", successTime2);
		map.put("retryCount", retryCount);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			ServiceResult<List<EmailLog>> result = serviceFactory.getEmailLogService().selectEmailLogPage(type, userid,
					storeId, email, title, content, state, sendTimeBegin, sendTimeEnd, successTimeBegin,
					successTimeEnd, retryCount, page.currentPage, page.pageSize, OrderType.DESC, "id");
			List<EmailLog> emailLogs = result.getReturnValue();
			int count = result.getReturnListSize();
			page.setEntityCount(count);
			map.put("emailloglist", emailLogs);
			map.put("emaillogListPage", page);
			return "stm/emaillog/emaillog_list";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/resend")
	public String reSend(ModelMap map)
	{
		List<EmailLog> notSendMailLogs = serviceFactory.getEmailLogService()
				.findNotsendEmailLogsOderByEmailLevel(null, EmailState.NOTSEND, OrderType.DESC, "sendLevel")
				.getReturnValue();
		if (notSendMailLogs == null || notSendMailLogs.size() == 0)
			return returnError(map, "没有待发送状态的邮件.");
		// 调用发送邮件接口
		for (EmailLog emailLog : notSendMailLogs)
			try
			{
				emailLog.setState(EmailState.SENDING);
				emailLog.setRetryCount(emailLog.getRetryCount() + 1);
				emailLog = serviceFactory.getEmailLogService().modify(emailLog).getReturnValue();
				MailSendUtil.sendMail(emailLog.getEmail(), emailLog.getTitle(), emailLog.getContent());
				System.out.println("Send Mail Ok." + emailLog.getEmail());
				emailLog.setState(EmailState.SENDED);
				emailLog.setSuccessTime(new Date());
				emailLog = serviceFactory.getEmailLogService().modify(emailLog).getReturnValue();
			}
			catch (AddressException e)
			{
				e.printStackTrace();
				return returnError(map, "邮件地址异常.");
			}
			catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
				return returnError(map, "邮件编码异常.");
			}
			catch (MessagingException e)
			{
				e.printStackTrace();
				return returnError(map, "邮件消息异常.");
			}

		return returnSuccess(map, "邮件发送成功！", "");
	}

}
